using System.Net.Sockets;

namespace GSN.Mail
{
    class POP3Exception : System.Exception
    {
        public POP3Exception(string message)
            : base(message)
        {

        }

    }

    /// <summary>
    /// A TcpClient with a few POP3-specific methods.
    /// Usually I don't like inheritance, but do it otherwise is a pain.
    /// </summary>
    class POP3Socket : TcpClient
    {
        public POP3Socket()
            : base(AddressFamily.InterNetwork)
        {
        }

        public void writeCommand(string str, params object[] args)
        {
            string cmd = string.Format(str, args);
            NetworkStream stream = GetStream();
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(cmd);
            stream.Write(bytes, 0, bytes.Length);
        }

        public string readResponseLine()
        {
            // @@@ test timeout

            NetworkStream stream = GetStream();
            stream.ReadTimeout = 1000 * 30;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            //string response = "";

            byte[] bytes = new byte[1];
            bytes[0] = 0;
            while (bytes[0] != '\n')
            {
                stream.Read(bytes, 0, 1);
                //response += System.Text.Encoding.ASCII.GetString(bytes);
                sb.Append(System.Text.Encoding.ASCII.GetString(bytes));
            }

            return sb.ToString();
        }

        public void verifyResponse(string response)
        {
            if (!(response.Substring(0, 3).ToLower() == "+ok"))
                throw new POP3Exception(response);
        }

    }
}
